﻿var $ = layui.$;

var id = location.search.split('=')[1]

var laydate = layui.laydate;
// 渲染
laydate.render({
    elem: '#pregnancyTestDate'
});

layui.use(['jquery'], function () {
    var $ = layui.jquery;

    //回显种母妊检数据
    function editSheepRes() {
        $.ajax({
            type: 'GET',
            url: `http://10.31.60.18:8000/ProduceGetRout/api/PregnancyPregnancyTestRead/GetPregnancyPregnancyTestInfo?id=${id}`, // 根据实际情况修改ControllerName和ActionName
            success: function (response) {
                var data = response.data
                $("#personCharge").val(data.personCharge)
                $("#pregnancyTestDate").val(data.pregnancyTestDate.split('T')[0])
                $("#auricle").val(data.auricle)
                $("#pregnancyTestResult").val(data.pregnancyTestResult)
                $("#pregnancyTestMethod").val(data.pregnancyTestMethod)
                $("#parityNumber").val(data.parityNumber)
                $("#pregnancyExaminationDays").val(data.pregnancyExaminationDays)
                $("#currentBuilding").val(data.currentBuilding)
                $("#currentField").val(data.currentField)
                $("#transferBuilding").val(data.transferBuilding)
                driveField()
                setTimeout(function () {
                    $("#driveField").val(data.driveField)
                }, 10)
            },
            error: function (xhr, status, error) {
                // 处理错误响应
                console.error(error);
            }
        })
    }

    //绑定耳号
    $(document).ready(function () {
        $.ajax({
            url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesAllInfo',
            type: 'get',
            dataType: 'json',
            success: function (res) {
                var enumData = res; // 直接使用返回的数据
                var select = $('#auricle');
                $.each(enumData, function (index, item) {
                    if (item.sheepType == "种母") {
                        // 使用正确的字段添加选项到下拉框中
                        var option = $('<option>').val(item.earNnumber).text(item.earNnumber);
                        select.append(option);
                    }
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });

    // 添加change事件监听器
    $('#auricle').change(function () {
        var selectedValue = $(this).val();

        $.ajax({
            url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesGetByEarNumberInfo?EarNumber=' + selectedValue,
            type: 'get',
            dataType: 'json',
            success: function (res) {
                if (res == undefined) {
                    $("#currentBuilding").val("")
                    $("#currentField").val("")
                } else {
                    $("#currentBuilding").val(res.cottageId)
                    $("#currentField").val(res.field)
                }
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });

    //绑定妊检结果
    $(document).ready(function () {
        $.ajax({
            url: 'http://10.31.60.18:8000/ProduceGetRout/api/PregnancyPregnancyTestRead/GetPregnancyTestResult',
            type: 'get',
            dataType: 'json',
            success: function (res) {
                var enumData = res; // 直接使用返回的数据
                var select = $('#pregnancyTestResult');
                $.each(enumData, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.name).text(item.name);
                    select.append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });

    //绑定栋舍
    var data = [];
    $(document).ready(function () {
        $.ajax({
            url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/CootList',
            type: 'get',
            dataType: 'json',
            success: function (res) {
                data = res; // 直接使用返回的数据
                var select = $('#transferBuilding');
                $.each(data, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.name).text(item.name);
                    select.append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });

    // 栋舍栏位二级联动
    $('#transferBuilding').change(function () {
        driveField()
    });

    function driveField() {
        var name = $("#transferBuilding").val();
        var id = 0;
        $.each(data, function (index, item) {
            if (name == item.name) {
                id = item.id;
            }
        });
        //监听到了下拉框选择的选项，传递过来
        $.get({
            url: 'http://10.31.60.18:8000/AuthorizationGetRout/api/Cottage/FieidList', // 后端枚举数据接口地址
            data: {
                id: id
            },
            dataType: "json",
            success: function (res) {
                $("#driveField").empty();
                var option = '<option value=" ">' + "请选择栏位" + '</option>';
                $("#driveField").append(option);
                $.each(res, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.name).text(item.name);
                    $('#driveField').append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    }

    //绑定妊检方式的枚举
    $(document).ready(function () {
        $.ajax({
            url: 'http://10.31.60.18:8000/ProduceGetRout/api/PregnancyPregnancyTestRead/GetPregnancyTestMethod', // 后端枚举数据接口地址
            type: 'get',
            dataType: 'json',
            success: function (res) {
                var enumData = res; // 直接使用返回的数据
                var select = $('#pregnancyTestMethod');
                $.each(enumData, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.name).text(item.name);
                    select.append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });

    $(function () {
        setTimeout(function () {
            editSheepRes()
        }, 100)
    })
});

function updRowBtn() {
    var inputValues = {
        id: id,
        personCharge: $("#personCharge").val(),
        pregnancyTestDate: $("#pregnancyTestDate").val(),
        auricle: $("#auricle").val(),
        pregnancyTestResult: $("#pregnancyTestResult").val(),
        pregnancyTestMethod: $("#pregnancyTestMethod").val(),
        parityNumber: $("#parityNumber").val() == "" ? null : $("#parityNumber").val(),
        pregnancyExaminationDays: $("#pregnancyExaminationDays").val() == "" ? null : $("#pregnancyExaminationDays").val(),
        currentBuilding: $("#currentBuilding").val(),
        currentField: $("#currentField").val(),
        transferBuilding: $("#transferBuilding").val(),
        driveField: $("#driveField").val(),
    }

    // 获取单个字段的输入框元素
    const personCharge = document.getElementById('personCharge');

    if (personCharge.value.trim() === '') {
        layer.msg('负责人不能为空！');
        return;
    }

    // 获取单个字段的输入框元素
    const pregnancyTestDate = document.getElementById('pregnancyTestDate');

    if (pregnancyTestDate.value.trim() === '') {
        layer.msg('妊检日期不能为空！');
        return;
    }

    // 获取单个字段的输入框元素
    const auricle = document.getElementById('auricle');

    if (auricle.value.trim() === '') {
        layer.msg('耳号不能为空！');
        return;
    }

    // 获取单个字段的输入框元素
    const pregnancyTestResult = document.getElementById('pregnancyTestResult');

    if (pregnancyTestResult.value.trim() === '') {
        layer.msg('妊检结果不能为空！');
        return;
    }

    // 获取单个字段的输入框元素
    const pregnancyTestMethod = document.getElementById('pregnancyTestMethod');

    if (pregnancyTestMethod.value.trim() === '') {
        layer.msg('妊检方式不能为空！');
        return;
    }

    // 在这里您可以执行其他操作，例如发送到服务器端进行处理
    $.ajax({
        type: 'PUT',
        url: 'http://10.31.60.18:8000/ProduceSetRout/api/PregnancyPregnancyTest/UpdatePregnancyPregnancyTest', // 根据实际情况修改ControllerName和ActionName
        data: JSON.stringify(inputValues),
        contentType: "application/json",
        success: function (response) {
            if (response.code == 200) {
                UpdArchives(inputValues)
                layer.msg('修改成功', { icon: 1 }, function () {
                    location.href = '/PregnancyPregnancyTest/PregnancyPregnancyTestShow'
                });
            } else if (response.code == 110) {
                layer.msg(response.msg);
            }
            else {
                layer.msg('修改失败');
            }
        },
        error: function (xhr, status, error) {
            // 处理错误响应
            console.error(error);
        }
    });
}

function UpdArchives(inputValues) {
    $.ajax({
        url: 'http://10.31.60.18:8000/ArchivesGetRout/api/Archives/ArchivesGetByEarNumberInfo?EarNumber=' + inputValues.auricle,
        type: 'get',
        dataType: 'json',
        success: function (data) {
            var values = {
                id: data.id,
                earNnumber: data.earNnumber,
                electronicEarNumber: data.electronicEarNumber,
                sheepBreed: data.sheepBreed,
                sheepGender: data.sheepGender,
                sheepBir: data.sheepBir,
                presence: data.presence,
                growthStage: data.growthStage,
                sheepType: data.sheepType,
                cottageId: inputValues.transferBuilding,
                field: inputValues.driveField,
                reproductiveState: data.reproductiveState,
                pregnancyTest: true,
                statusDays: data.statusDays,
                productionGrade: data.productionGrade,
                salesGrade: data.salesGrade,
                geneticGrade: data.geneticGrade,
                birthWeight: data.birthWeight,
                weaningDate: data.weaningDate,
                fatherEarNumber: data.fatherEarNumber,
                motherEarNumber: data.motherEarNumber,
                dayAge: data.dayAge,
                monthAge: data.monthAge,
                weaningAge: data.weaningAge,
                sheepBir: data.sheepBir,
                archivesRemark: data.archivesRemark,
                archivesPicture: data.archivesPicture,
                placeBirth: data.placeBirth,
                inDate: data.inDate
            }

            // 在这里您可以执行其他操作，例如发送到服务器端进行处理
            $.ajax({
                type: 'PUT',
                url: 'http://10.31.60.18:8000/ArchivesSetRout//api/Archives/ArchivesUpdate', // 根据实际情况修改ControllerName和ActionName
                data: JSON.stringify(values),
                contentType: "application/json",
                success: function (response) {
                    console.log(response)
                },
                error: function (xhr, status, error) {
                    // 处理错误响应
                    console.error(error);
                }
            });
        },
        error: function () {
            // 处理 AJAX 请求失败的情况
            console.error('Failed to fetch data for dropdown.');
        }
    });
}